package com.lemner.www.hongyu.Fragement;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lemner.www.hongyu.Activity.FileUtils;
import com.lemner.www.hongyu.Activity.LoginActivity;
import com.lemner.www.hongyu.Activity.MainActivity;
import com.lemner.www.hongyu.Activity.ReviseActivity;
import com.lemner.www.hongyu.Bean.Userbean;
import com.lemner.www.hongyu.R;

import java.io.File;


public class MyFragment extends Fragment implements View.OnClickListener {
    private View view;
    private TextView tv_username, tv_address, tv_phone, tv_card, tv_exit, tv_revise;
    private ImageView iv_head;
    private RatingBar rb_score;
    private Userbean.DataBean date;
    private File mTmpFile;
    private File mCropImageFile;
    private static final int REQUEST_CAMERA = 100;
    private static final int REQUEST_GALLERY = 101;
    private static final int REQUEST_CROP = 102;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_my, container, false);
        InitView();
        Bundle bundle = getArguments();
        date = (Userbean.DataBean) bundle.getSerializable("date");
        return view;
    }

    public void InitView() {
        tv_username = (TextView) view.findViewById(R.id.tv_username);
        tv_phone = (TextView) view.findViewById(R.id.tv_phone);
        tv_address = (TextView) view.findViewById(R.id.tv_address);
        tv_card = (TextView) view.findViewById(R.id.tv_card);
        tv_exit = (TextView) view.findViewById(R.id.tv_exit);
        tv_revise = (TextView) view.findViewById(R.id.tv_revise);
        rb_score = (RatingBar) view.findViewById(R.id.rb_score);
        iv_head = (ImageView) view.findViewById(R.id.iv_head);
        iv_head.setOnClickListener(this);
        tv_revise.setOnClickListener(this);
        tv_exit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_exit:
                Intent intent0 = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent0);
                Toast.makeText(getActivity(),"退出成功",Toast.LENGTH_SHORT).show();
                break;
            case R.id.tv_revise:
                Intent intent1 = new Intent(getActivity(), ReviseActivity.class);
                intent1.putExtra("date",date);
                startActivity(intent1);
                break;
            case R.id.iv_head:
                setupDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (date != null) {
            tv_username.setText(date.getUser().getUsername());
            tv_phone.setText(date.getUser().getPhone());
            tv_card.setText(date.getUser().getCard_id());
            tv_address.setText(date.getUser().getHome_address());
            rb_score.setRating(date.getUser().getEvaluation());
        } else {
            Toast.makeText(getActivity(), "没能获取到数据", Toast.LENGTH_SHORT).show();
        }
    }

    private void setupDialog() {
        final String[] items = {"拍照", "相册"};
        AlertDialog.Builder listDialog = new AlertDialog.Builder(getActivity());
        listDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (i == 0) {
                    startCameraIntent();
                } else if (i == 1) {
                    gallery();
                }
            }
        });
        listDialog.show();
    }

    private void gallery() {   //访问图库
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, REQUEST_GALLERY);
    }

    public void startCameraIntent() {  //访问相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mTmpFile = new File(FileUtils.createRootPath(getContext()) + "/" + System.currentTimeMillis() + ".jpg");
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion < 24) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
            startActivityForResult(intent, REQUEST_CAMERA);
        } else {
            /**
             * 检查权限
             */
            if ((ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED)
                    || (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED)
                    || (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED)) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.CAMERA)) {
                    // 用户拒绝过这个权限了，应该提示用户，为什么需要这个权限。
                    Toast.makeText(getContext(), " 用户拒绝过这个权限了，应该提示用户，为什么需要这个权限。",
                            Toast.LENGTH_SHORT).show();
                    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
                    builder.setTitle("权限提醒");
                    builder.setMessage("访问照相机");
                    builder.setNegativeButton("拒绝", null);
                    builder.setPositiveButton("接受", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ActivityCompat.requestPermissions(getActivity(), new String[]{
                                    android.Manifest.permission.CAMERA,
                                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        }
                    });
                    builder.show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{
                            android.Manifest.permission.CAMERA,
                            android.Manifest.permission.READ_EXTERNAL_STORAGE,
                            android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

                }
            }
            else{
                // 有权限了。
                Uri imageUri = FileProvider.getUriForFile(getContext(), "com.lemner.www.hongyu.FileProvider",
                        mTmpFile);//这里进行替换uri的获得方式
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//这里加入flag
                startActivityForResult(intent, REQUEST_CAMERA);
            }

        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED
                && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
            // 权限被用户同意，可以做你要做的事情了。
            switch (requestCode) {
                case 1:
                    Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri imageUri = FileProvider.getUriForFile(getContext(), "com.lemner.www.hongyu.FileProvider", mTmpFile);
                    intent1.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//这里加入flag
                    startActivityForResult(intent1, REQUEST_CAMERA);
                    break;
                default:
                    break;
            }
        }

        else {
            // 权限被用户拒绝了，可以提示用户,关闭界面等等。
            Toast.makeText(getContext(), "取消操作", Toast.LENGTH_SHORT).show();
        }
       /* return;*/
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CAMERA:
                if (resultCode == MainActivity.RESULT_OK) {
                    crop(mTmpFile.getAbsolutePath());
                } else {
                    Toast.makeText(getActivity(), "拍照失败", Toast.LENGTH_SHORT).show();
                }
                break;

            case REQUEST_CROP:
                if (resultCode == MainActivity.RESULT_OK) {
                    iv_head.setImageURI(Uri.fromFile(mCropImageFile));
                } else {
                    Toast.makeText(getActivity(), "截图失败", Toast.LENGTH_SHORT).show();
                }
                break;

            case REQUEST_GALLERY:
                if (resultCode == MainActivity.RESULT_OK && data != null) {
                    String imagePath = handleImage(data);
                    crop(imagePath);
                } else {
                    Toast.makeText(getActivity(), "打开图库失败", Toast.LENGTH_SHORT).show();
                }
                break;

        }
    }

    private void crop(String imagePath) {
        mCropImageFile = getmCropImageFile();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(getImageContentUri(new File(imagePath)), "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 500);
        intent.putExtra("outputY", 500);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCropImageFile));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, REQUEST_CROP);
    }

    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = getActivity().getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return getActivity().getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    //获取裁剪的图片保存地址
    private File getmCropImageFile() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(getActivity().getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
            return file;
        }
        return null;
    }

    private String handleImage(Intent data) {
        Uri uri = data.getData();
        String imagePath = null;
        if (Build.VERSION.SDK_INT >= 19) {
            if (DocumentsContract.isDocumentUri(getActivity(), uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    String id = docId.split(":")[1];
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("" +
                            "content://downloads/public_downloads"), Long.valueOf(docId));
                    imagePath = getImagePath(contentUri, null);
                }
            } else if ("content".equals(uri.getScheme())) {
                imagePath = getImagePath(uri, null);
            }
        } else {
            imagePath = getImagePath(uri, null);
        }
        return imagePath;
    }

    private String getImagePath(Uri uri, String seletion) {
        String path = null;
        Cursor cursor = getActivity().getContentResolver().query(uri, null, seletion, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


}